<?php
namespace app\index\service;

use app\index\model\CityModel;
use app\index\model\DeptModel;
use app\index\model\FileModel;
use app\index\model\FlowBillModel;
use app\index\model\FlowLogModel;
use app\index\model\FlowNodeModel;
use app\index\model\FlowPromerModel;
use app\index\model\FlowShenlogModel;
use app\index\model\LogListModel;
use app\index\model\OptionModel;
use app\index\model\TodoModel;
use app\index\model\UserModel;
use app\index\model\WorkerModel;
use app\index\worker\Worker;
use think\Exception;
use think\facade\Env;

class OptService extends CommonService
{

    public function add_flow_shenlog($task, $chuname, $chuer, $explain='', $promer='', $files='', $qian_id=0, $qian=''){
        return FlowShenlogModel::insert([
            'comid' => $this->userinfo['comid'],
            'billid' => $task['billid'],
            'name' => $task['name'],
            'chuname' => $chuname,
            'explain' => $explain,
            'chuer' =>  $chuer,
            'promer' => $promer,
            'files' => $files,
            'qian_id' => $qian_id,
            'qian' => $qian,
            'created_user' => $this->userinfo['id'],
            'created_at' => date("Y-m-d H:i:s")
        ]);
    }

    public function add_flow_shenlog_direct($bill, $chuname, $chuer, $explain=''){
        return FlowShenlogModel::insert([
            'comid' => $this->userinfo['comid'],
            'billid' => $bill['id'],
            'chuname' => $chuname,
            'chuer' =>  $chuer,
            'explain' =>  $explain,
            'created_user' => $this->userinfo['id'],
            'created_at' => date("Y-m-d H:i:s")
        ]);
    }


    public function add_flow_log($name, $table, $mid, $statusname='', $explain=''){
        return FlowLogModel::insert([
            'comid' => $this->userinfo['comid'],
            'name' => $name,
            'table' => $table,
            'mid' => $mid,
            'statusname' => $statusname,
            'explain' => $explain,
            'created_user' => $this->userinfo['id'],
            'created_at' => date("Y-m-d H:i:s")
        ]);
    }

    public function add_log_list($butname, $table, $mid, $name){
        return LogListModel::insert([
            'comid' => $this->userinfo['comid'],
            'name' => $name,
            'butname' => $butname,
            'table' => $table,
            'mid' => $mid,
            'ip' => request()->ip(),
            'uid' => $this->userinfo['id'],
            'realname' => $this->userinfo['realname'].' '.$this->userinfo['tel'],
            'deptname' => DeptModel::get_name_by_pk($this->userinfo['deptid']),
            'optdt' => date("Y-m-d H:i:s")
        ]);
    }

    public function get_file($table='', $mid=0){
        $data = FileModel::field('id,table,mid,name,ext,size,encpath,fileplain,created_user,created_at')
            ->where(['table'=>$table,'mid'=>$mid,'comid'=>$this->userinfo['comid']])->select()->toArray();
        foreach ($data as &$item){
            $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
        }
        return $data;
    }



    public function relation_file($files=[], $table = '', $mid=0){
        FileModel::where(['table'=>$table,'mid'=>$mid])->update(['mid'=>0,'table'=>'']);
        foreach ($files as $vv){
            $vv['fileplain'] = isset($vv['fileplain']) ? $vv['fileplain'] : '';
            FileModel::where(['id'=>$vv['id']])->update(['mid'=>$mid,'table'=>$table,'fileplain'=>$vv['fileplain']]);
        }
        return true;
    }



    public function get_base_info($num = '')
    {
        if(empty($num)){
            return [];
        }
        $option_id = OptionModel::get_pk_by_num($this->userinfo['comid'], $num);
        if(!$option_id){
            return [];
        }
        return $this->get_option_all($option_id);
    }

    public function get_base_order($num = '')
    {
        if(empty($num)){
            return [];
        }
        $option_id = OptionModel::get_pk_by_num($this->userinfo['comid'], $num);
        if(!$option_id){
            return [];
        }

        $data = [];
        $list = OptionModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'topid'=>$option_id])
            ->order('keyid ASC')->select()->toArray();
        foreach ($list as $v){
            $data[$v['keyid']] = $v['name'];
        }

        return $data;
    }

    public function get_option_all($pid=0){
//        $data = OptionModel::field('id as pid,name as value,name')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>$pid])->order('sort ASC')->select()->toArray();
        $data = OptionModel::field('id,keyid as value,name as title,name')
            ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>$pid])
            ->order('sort ASC')->select()->toArray();
        foreach ($data as &$item){
            $item['children'] = $this->get_option_all($item['id']);
        }
        return $data;
    }

    public function get_base_info_name($num = '')
    {
        if(empty($num)){
            return [];
        }
        $option_id = OptionModel::get_pk_by_num($this->userinfo['comid'], $num);
        if(!$option_id){
            return [];
        }
        return $this->get_option_all($option_id);
    }

    public function get_option_all_name($pid=0){
//        $data = OptionModel::field('id as pid,name as value,name')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>$pid])->order('sort ASC')->select()->toArray();
        $data = OptionModel::field('id,name as value,name as title,name')
            ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>$pid])
            ->order('sort ASC')->select()->toArray();
        foreach ($data as &$item){
            $item['children'] = $this->get_option_all($item['id']);
        }
        return $data;
    }


    public function get_base_showname($num = '', $keyid)
    {
        if(empty($num) || empty($keyid)){
            return '';
        }
        $option_id = OptionModel::get_pk_by_num($this->userinfo['comid'], $num);
        $name = OptionModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'topid'=>$option_id, 'keyid'=>$keyid])->value('name');
        return $name;
    }

    public function get_base_showname_duo($num = '', $keyids)
    {
        if(empty($num) || empty($keyids)){
            return '';
        }
        $option_id = OptionModel::get_pk_by_num($this->userinfo['comid'], $num);
        $name = OptionModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'topid'=>$option_id])
            ->where('keyid','in',$keyids)
            ->column('name');
        return implode(',', $name);
    }

    public function get_option_ids($id){
        static $ids = [];
        $opt_data = OptionModel::where(['pid'=>$id])->select();
        if($opt_data){
            foreach ($opt_data as $item){
                $ids[] = $item['keyid'];
                $this->get_option_ids($item['id']);
            }
        }
        return $ids;
    }

    public function get_city_cader(){
        $path = './data/city.json';
        if(file_exists($path)){
            $cityJson = file_get_contents($path);
            if($cityJson){
                return json_decode($cityJson, true);
            }
        }


        $data = [];
        $one = CityModel::field('id as code,name as address,first')->where(['pid'=>0])->order('first ASC')->select()->toArray();
        $one_chu = [];
        foreach ($one as $vv){
            if(in_array($vv['first'],['A','B','C','D','E','F','G'])){
                if(isset($one_chu['A-G'])){
                    $one_chu['A-G'][] = $vv;
                }else{
                    $one_chu['A-G'] = [$vv];
                }
            }
            if(in_array($vv['first'],['H','I','J','K'])){
                if(isset($one_chu['H-K'])){
                    $one_chu['H-K'][] = $vv;
                }else{
                    $one_chu['H-K'] = [$vv];
                }
            }
            if(in_array($vv['first'],['L','M','N','O','P','Q','R','S'])){
                if(isset($one_chu['L-S'])){
                    $one_chu['L-S'][] = $vv;
                }else{
                    $one_chu['L-S'] = [$vv];
                }
            }
            if(in_array($vv['first'],['T','U','V','W','X','Y','Z'])){
                if(isset($one_chu['T-Z'])){
                    $one_chu['T-Z'][] = $vv;
                }else{
                    $one_chu['T-Z'] = [$vv];
                }
            }
        }
        $data[0] = $one_chu;



        foreach ($one as $k=>$v){
            $two = CityModel::field('id,name')->where(['pid'=>$v['code']])->select()->toArray();
            $data[$v['code']] = [];
            foreach ($two as $kk=>$vv){
                $data[$v['code']][$vv['id']] = $vv['name'];
                $data[$vv['id']] = [];
                $three = CityModel::field('id,name')->where(['pid'=>$vv['id']])->select()->toArray();
                foreach ($three as $kkk=>$vvv){
                    $data[$vv['id']][$vvv['id']] = $vvv['name'];
                }
            }
        }

        file_put_contents($path,json_encode($data));
        return $data;
    }

    public function get_city_cader_mob(){
        $deaArr = ['code'=>'请选择','name'=>'请选择','childs'=>[]];
        $data = CityModel::field('name,name as code,id')->where(['pid'=>0])->select()->toArray();
        foreach ($data as $k=>$v){
            $two = CityModel::field('name,name as code,id')->where(['pid'=>$v['id']])->select()->toArray();
            foreach ($two as $kk=>$vv){
                $threeArr = CityModel::field('name,name as code,id')->where(['pid'=>$vv['id']])->select()->toArray();
                array_unshift($threeArr, $deaArr);
                $two[$kk]['childs'] = $threeArr;
            }

            array_unshift($two, $deaArr);
            $data[$k]['childs'] = $two;
        }

        dump(json_encode($data));die;
    }

    public function delete_city_cader(){
        $path = './data/city.json';
        if(file_exists($path)){
            unlink($path);
        }
        return true;
    }


    public function check_option_exists($num, $val){
        $top_data = OptionModel::where(['deleted_user'=>0,'num'=>$num])->find();
        if(!$top_data){
            return false;
        }
        return !!OptionModel::where(['deleted_user'=>0,'keyid'=>$val,'topid'=>$top_data['id']])->find();
    }


    public function add_todo($uids, $name, $mess, $mid, $table, $meter=''){
        if(empty($uids)){
            return false;
        }
        $uidsarr = array_unique(explode(',', $uids));

        foreach ($uidsarr as $uid){
            $user = UserModel::get_info_by_pk($uid);
            if(!$user || $user['deleted_user'] > 0){
                continue;
            }

            $ins = [];
            $ins['table'] = $table;
            $ins['meter'] = $meter;
            $ins['name'] = $name;
            $ins['mess'] = $mess;
            $ins['mid'] = $mid;
            $ins['uid'] = $uid;
            $ins['tododt'] = date("Y-m-d H:i:s");
            TodoModel::insert($ins);
            (new WorkerService())->add_worker_todo($uid, $name, $mess, $mid, $table, $meter);
        }
        return true;
    }


    /**
     * 批量下载附件 打包zip
     * @param $comid
     * @param $uid
     * @param string $ids
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function down_allfile($comid,$uid, $ids=''){
        if(empty($ids)){
            throw new Exception("操作失败");
        }
        $id_arr = explode(',', $ids);
        $file_dir = 'tmp_zip/';
        $filename = 'user_'.$uid.'.zip';

        if(file_exists($file_dir.$filename)){
            unlink($file_dir.$filename);
        }

        $zip = new \ZipArchive();
        $res = $zip->open($file_dir.$filename, $zip::CREATE);
        if ($res === TRUE) {
            foreach ($id_arr as $fileid) {
                if($fileid < 1){
                    continue;
                }
                $_file = FileModel::where(['id'=>$fileid])->find();
                if(!$_file || $_file['comid'] != $comid){
                    throw new Exception("操作失败");
                }
                $zip->addFile($_file['oripath']);
            }
        }
        $rest = $zip->close();
        if(file_exists($file_dir.$filename)){
            return $file_dir.$filename;
//            $file = fopen ( $file_dir.$filename, "rb" );
//            Header ( "Content-type: application/octet-stream" );
//            Header ( "Accept-Ranges: bytes" );
//            Header ( "Accept-Length: " . filesize ( $file_dir.$filename ) );
//            Header ( "Content-Disposition: attachment; filename=附件打包下载.zip");
//            ob_clean();
//            flush();
//            echo fread ( $file, filesize ( $file_dir.$filename ) );
//            fclose ( $file );
//            exit ();
        }else{
            throw new Exception('下载失败');
        }
    }


    public function down_watermark_zip($id_arr='', $filename = '', $watermark=''){
        if(empty($id_arr)){
            throw new Exception("暂无附件，无法提供下载!");
        }

        $file_dir = 'tmp_zip/';
        $filename = $filename.'.zip';

        if(file_exists($file_dir.$filename)){
            unlink($file_dir.$filename);
        }
        $rootPath = Env::get('root_path');
        $dir = uniqid();
        $crePath = Env::get('root_path').'public/downdata/'.$dir.'/';
        if(!is_dir(Env::get('root_path').'public/downdata/')){
            mkdir(Env::get('root_path').'public/downdata/');
        }

        if(!is_dir($crePath)){
            mkdir($crePath);
        }

        $del_list = [];
        $zip = new \ZipArchive();
        $res = $zip->open($file_dir.$filename, $zip::CREATE);
        if ($res === TRUE) {

            foreach ($id_arr as $fileid) {
                if($fileid < 1){
                    continue;
                }
                $_file = FileModel::where(['id'=>$fileid])->find();
                if(!$_file || $_file['comid'] != $this->userinfo['comid']){
                    throw new Exception("操作失败");
                }

                // 复制文件的地址
                $copy_url = $rootPath.mb_substr($_file['oripath'],3);
                // 判断文件是否为图片
                if(in_array($_file['ext'],['jpg','png','jpeg','JPG','PNG','JPEG'])){
                    if(!is_file($copy_url)){
                        throw new Exception("操作失败");
                    }
                    watermark($copy_url, $crePath.$_file['name'], $watermark);
                    $del_list[] = $crePath.$_file['name'];
                }else{
                    copy($copy_url, $crePath.$_file['name']);
                    $del_list[] = $crePath.$_file['name'];
                }
                $zip->addFile('./downdata/'.$dir.'/'.$_file['name']);
            }
            $del_list[] = $crePath;
        }

        $zip->close();
        if(file_exists($file_dir.$filename)){
            // 删除生成的文件
            foreach ($del_list as $f){
                if(is_dir($f)){
                    deldir_f($f);
                }else{
                    @unlink($f);
                }
            }
            return $file_dir.$filename;
        }else{
            throw new Exception('下载失败');
        }
    }

    public function down_watermark_zip2($comid, $id_arr='', $filename = '', $watermark=''){
        if(empty($id_arr)){
            throw new Exception("暂无附件，无法提供下载!");
        }

        $file_dir = 'tmp_zip/';
        $filename = $filename.'.zip';
        $filename = iconv('utf-8', 'gbk', $filename);
        if(file_exists($file_dir.$filename)){
            unlink($file_dir.$filename);
        }

        $del_list = [];
        $zip = new \ZipArchive();
        $res = $zip->open($file_dir.$filename, $zip::CREATE);
        if ($res === TRUE) {
            foreach ($id_arr as $fileid) {
                if($fileid < 1){
                    continue;
                }
                $_file = FileModel::where(['id'=>$fileid])->find();
                if(!$_file || $_file['comid'] != $comid){
                    throw new Exception("操作失败");
                }
                // 判断是人员附件还是证书附件，查询人员名称,创建文件夹
                if($_file['mtype'] == 'cert'){
                    $personid = CertModel::where('id',$_file['mid'])->value('personid');
                    $personname = CertpersonModel::where('id',$personid)->value('name');
                }else{
                    $personname = CertpersonModel::where('id',$_file['mid'])->value('name');
                }
                if(!is_dir(Env::get('root_path').'public\\'.iconv('utf-8', 'gbk', $personname))){
                    mkdir(iconv('utf-8', 'gbk', $personname));
                }

                // 复制文件的地址
                $copy_url = Env::get('root_path').mb_substr($_file['filepath'],3);
                // 判断文件是否为图片
                if(in_array($_file['fileext'],['jpg','png','jpeg','JPG','PNG','JPEG'])){
                    if(!is_file($copy_url)){
                        throw new Exception("操作失败");
                    }
                    watermark($copy_url, iconv('utf-8', 'gbk', $_file['filename']), $watermark);
                    copy(iconv('utf-8', 'gbk', $_file['filename']), './'.iconv('utf-8', 'gbk', $personname).'/'.iconv('utf-8', 'gbk', $_file['filename']));
                    $del_list[] = Env::get('root_path').'public\\'.iconv('utf-8', 'gbk', $_file['filename']);
                }else{
                    copy($copy_url, './'.iconv('utf-8', 'gbk', $personname).'/'.iconv('utf-8', 'gbk', $_file['filename']));
                }
                $del_list[] = Env::get('root_path').'public\\'.iconv('utf-8', 'gbk', $personname);

                $zip->addFile('./'.iconv('utf-8', 'gbk', $personname).'/'.iconv('utf-8', 'gbk', $_file['filename']));
            }
        }

        $zip->close();
        if(file_exists($file_dir.$filename)){
            // 删除生成的文件
            foreach ($del_list as $f){
                if(is_dir($f)){
                    deldir_f($f);
                }else{
                    @unlink($f);
                }
            }

            return iconv('gbk', 'utf-8', $file_dir.$filename);
        }else{
            throw new Exception('下载失败');
        }
    }

}
